<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>简化WebRTC测试</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        margin: 20px;
      }
      video {
        width: 300px;
        height: 200px;
        border: 2px solid #ccc;
        margin: 10px;
      }
      button {
        padding: 10px 20px;
        margin: 5px;
      }
      .container {
        display: flex;
        gap: 20px;
      }
      .panel {
        border: 1px solid #ddd;
        padding: 20px;
        border-radius: 8px;
      }
      .log {
        background: #f5f5f5;
        padding: 10px;
        height: 200px;
        overflow-y: auto;
        font-family: monospace;
        font-size: 12px;
      }
    </style>
  </head>
  <body>
    <h1>简化WebRTC测试（仅局域网）</h1>

    <div class="container">
      <div class="panel">
        <h3>主播端</h3>
        <video id="localVideo" autoplay muted playsinline></video><br />
        <button id="startBtn">开始直播</button>
        <button id="stopBtn" disabled>停止直播</button>
        <div>直播间ID: <span id="streamId">-</span></div>
      </div>

      <div class="panel">
        <h3>观众端</h3>
        <video id="remoteVideo" autoplay playsinline controls></video><br />
        <input type="text" id="roomInput" placeholder="输入直播间ID" />
        <button id="joinBtn">加入</button>
        <button id="leaveBtn" disabled>离开</button>
      </div>
    </div>

    <div class="panel">
      <h3>调试日志</h3>
      <div id="log" class="log"></div>
      <button onclick="clearLog()">清空日志</button>
    </div>

    <script>
      // 简化的WebRTC配置（仅局域网）
      const config = {
        iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
        // 强制仅使用HOST候选（局域网内直连）
        iceTransportPolicy: "all",
      };

      let localConnection = null;
      let remoteConnection = null;
      let localStream = null;
      let isOfferer = false;

      const localVideo = document.getElementById("localVideo");
      const remoteVideo = document.getElementById("remoteVideo");
      const startBtn = document.getElementById("startBtn");
      const stopBtn = document.getElementById("stopBtn");
      const joinBtn = document.getElementById("joinBtn");
      const leaveBtn = document.getElementById("leaveBtn");
      const streamIdSpan = document.getElementById("streamId");
      const roomInput = document.getElementById("roomInput");
      const logDiv = document.getElementById("log");

      function log(message) {
        console.log(message);
        const time = new Date().toLocaleTimeString();
        logDiv.innerHTML += `[${time}] ${message}\n`;
        logDiv.scrollTop = logDiv.scrollHeight;
      }

      function clearLog() {
        logDiv.innerHTML = "";
      }

      // 简化版本：直接在同一页面模拟两个对等端
      startBtn.addEventListener("click", async () => {
        try {
          log("📹 获取本地媒体流...");
          localStream = await navigator.mediaDevices.getUserMedia({
            video: { width: 640, height: 480 },
            audio: true,
          });
          localVideo.srcObject = localStream;

          log("🔗 创建本地PeerConnection...");
          localConnection = new RTCPeerConnection(config);

          // 添加本地流
          localStream.getTracks().forEach((track) => {
            localConnection.addTrack(track, localStream);
            log(`📡 添加轨道: ${track.kind}`);
          });

          // ICE候选事件
          localConnection.onicecandidate = (event) => {
            if (event.candidate) {
              const candidate = event.candidate.candidate;
              const type = candidate.includes("typ host")
                ? "HOST"
                : candidate.includes("typ srflx")
                ? "STUN"
                : candidate.includes("typ relay")
                ? "TURN"
                : "OTHER";
              log(`📡 本地ICE候选 [${type}]: ${candidate}`);

              // 在真实应用中，这里会通过信令服务器发送
              if (remoteConnection) {
                remoteConnection
                  .addIceCandidate(event.candidate)
                  .then(() => log("✅ 远程端添加ICE候选成功"))
                  .catch((err) =>
                    log(`❌ 远程端添加ICE候选失败: ${err.message}`)
                  );
              }
            } else {
              log("✅ 本地ICE候选收集完成");
            }
          };

          // 连接状态监听
          localConnection.onconnectionstatechange = () => {
            log(`🔗 本地连接状态: ${localConnection.connectionState}`);
          };

          localConnection.oniceconnectionstatechange = () => {
            log(`🧊 本地ICE连接状态: ${localConnection.iceConnectionState}`);
          };

          const roomId = "room_" + Math.random().toString(36).substr(2, 6);
          streamIdSpan.textContent = roomId;

          startBtn.disabled = true;
          stopBtn.disabled = false;

          log(`🎬 直播已开始，房间ID: ${roomId}`);
        } catch (error) {
          log(`❌ 开始直播失败: ${error.message}`);
        }
      });

      joinBtn.addEventListener("click", async () => {
        try {
          if (!localConnection) {
            log("❌ 请先开始直播");
            return;
          }

          log("🔗 创建远程PeerConnection...");
          remoteConnection = new RTCPeerConnection(config);

          // 接收远程流
          remoteConnection.ontrack = (event) => {
            log("🎥 收到远程流!");
            const [remoteStream] = event.streams;
            remoteVideo.srcObject = remoteStream;

            // 尝试播放
            remoteVideo
              .play()
              .then(() => log("✅ 视频播放成功!"))
              .catch((err) => {
                log(`⚠️ 自动播放失败: ${err.message}`);
                log("👆 请手动点击播放按钮");
              });
          };

          // ICE候选事件
          remoteConnection.onicecandidate = (event) => {
            if (event.candidate) {
              const candidate = event.candidate.candidate;
              const type = candidate.includes("typ host")
                ? "HOST"
                : candidate.includes("typ srflx")
                ? "STUN"
                : candidate.includes("typ relay")
                ? "TURN"
                : "OTHER";
              log(`📡 远程ICE候选 [${type}]: ${candidate}`);

              // 添加到本地连接
              localConnection
                .addIceCandidate(event.candidate)
                .then(() => log("✅ 本地端添加ICE候选成功"))
                .catch((err) =>
                  log(`❌ 本地端添加ICE候选失败: ${err.message}`)
                );
            } else {
              log("✅ 远程ICE候选收集完成");
            }
          };

          // 连接状态监听
          remoteConnection.onconnectionstatechange = () => {
            log(`🔗 远程连接状态: ${remoteConnection.connectionState}`);
          };

          remoteConnection.oniceconnectionstatechange = () => {
            log(`🧊 远程ICE连接状态: ${remoteConnection.iceConnectionState}`);
            if (remoteConnection.iceConnectionState === "connected") {
              log("🎉 P2P连接建立成功!");
            }
          };

          // 开始offer/answer协商
          log("📝 创建offer...");
          const offer = await localConnection.createOffer();
          await localConnection.setLocalDescription(offer);
          log("📤 设置本地描述(offer)");

          await remoteConnection.setRemoteDescription(offer);
          log("📥 设置远程描述(offer)");

          log("📝 创建answer...");
          const answer = await remoteConnection.createAnswer();
          await remoteConnection.setLocalDescription(answer);
          log("📤 设置本地描述(answer)");

          await localConnection.setRemoteDescription(answer);
          log("📥 设置远程描述(answer)");

          joinBtn.disabled = true;
          leaveBtn.disabled = false;

          log("🤝 开始P2P连接协商...");
        } catch (error) {
          log(`❌ 加入直播失败: ${error.message}`);
        }
      });

      stopBtn.addEventListener("click", () => {
        if (localStream) {
          localStream.getTracks().forEach((track) => track.stop());
          localVideo.srcObject = null;
        }
        if (localConnection) {
          localConnection.close();
          localConnection = null;
        }
        if (remoteConnection) {
          remoteConnection.close();
          remoteConnection = null;
        }

        startBtn.disabled = false;
        stopBtn.disabled = true;
        joinBtn.disabled = false;
        leaveBtn.disabled = true;
        streamIdSpan.textContent = "-";

        log("🛑 直播已停止");
      });

      leaveBtn.addEventListener("click", () => {
        if (remoteConnection) {
          remoteConnection.close();
          remoteConnection = null;
        }
        remoteVideo.srcObject = null;

        joinBtn.disabled = false;
        leaveBtn.disabled = true;

        log("👋 已离开直播间");
      });

      log("🚀 简化WebRTC测试页面已就绪");
      log("📋 测试步骤: 1.点击开始直播 2.点击加入 3.观察连接过程");
    </script>
  </body>
</html>
